package com.hsd.whb.utils;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.GetObjectRequest;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;
import org.springframework.http.MediaType;

import java.io.File;
import java.io.InputStream;

/*
 * @auther: wangjiacai
 *
 * @create: 2018-04-15 21:08:55
 */
public class COSUtil {

    private static String secretId = "AKIDkdOzTolwjtwtfJKvBKJ7KQ23veGk582p";
    private static String secretKey = "pYBnHZihTINM9pMhKo7DvYgiZmpmY8Xq";
    private static String region = "ap-guangzhou";
    private static String bucketName = "huiwubao-1252042671";
    private static COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
    private static ClientConfig clientConfig = new ClientConfig(new Region(region));

    public static void uploadFile(File file, String key) {
        COSClient cosClient = getCosClient();
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, file);
        while (true) {
            try {
                PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
                break;
            } catch (Exception e) {
            }
        }
        cosClient.shutdown();
    }

    public static void uploadFile(InputStream inputStream, String key) {
        COSClient cosClient = getCosClient();
        ObjectMetadata objectMetadata = new ObjectMetadata();
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, inputStream, objectMetadata);
        while (true) {
            try {
                PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
                break;
            } catch (Exception e) {
            }
        }
        cosClient.shutdown();
    }

    public static void downloadFile(File file, String key) {
        COSClient cosClient = getCosClient();
        GetObjectRequest getObjectRequest = new GetObjectRequest(bucketName, key);
        ObjectMetadata downObjectMeta = cosClient.getObject(getObjectRequest, file);
        cosClient.shutdown();
    }

    public static void deleteFile(String key) {
        COSClient cosClient = getCosClient();
        cosClient.deleteObject(bucketName, key);
        cosClient.shutdown();
    }

    public static COSClient getCosClient() {
        return new COSClient(cred, clientConfig);
    }

    public static void main(String[] args) {
        File file = new File("src/main/resources/sound_demo1.pcm");
        uploadFile(file, "test");
        downloadFile(new File("src/main/resources/test1.pcm"), "test");
        deleteFile("test");
    }
}
